package ai.mspbots.service.projectb.service.impl;

import ai.mspbots.service.projectb.config.Constant;
import ai.mspbots.service.projectb.entity.UserEntity;
import ai.mspbots.service.projectb.mapper.UserMapper;
import ai.mspbots.service.projectb.service.IUserService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.skywalking.apm.toolkit.trace.ActiveSpan;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {
    private static final Logger logger = LogManager.getLogger(UserServiceImpl.class);

    private AtomicLong counter = new AtomicLong(0);
    @Trace
    @Override
    public void saveUser(String name) {
        if (counter.getAndIncrement() % Constant.SAMPLE_RATE == 0) {
            logger.debug("Save user {}", name);
        }
        ActiveSpan.tag("user.name", name);
        Connection connection = null;
        this.save(new UserEntity(name));
    }

    @Trace(operationName = "selectUser")
    @Override
    public void selectUser(String name) {
        if (counter.getAndIncrement() % Constant.SAMPLE_RATE == 0) {
            logger.debug("select user {}", name);
        }
        ActiveSpan.tag("user.name", name);
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotEmpty(name), UserEntity::getName, name);
        queryWrapper.last("limit 1");
        this.getOne(queryWrapper);
    }
}
